<template>
  <div id="pkView" class="g-container">
    <a-layout style="height: 100%;">
      <a-layout-header>
        <div style="text-align: center">
          <div id="countupTimer">
            <div class="timer">
              <div class="timer-text">
                <span v-if="hour > 0"> {{ hour }} :</span>
                <span v-if="minute > 0 || hour > 0">{{ minute }} :</span>
                {{ second }}
              </div>
            </div>
          </div>
        </div>
      </a-layout-header>
      <a-layout-content>
        <a-row>
          <a-col :span="7">
            <UserBoard :user="myself"/>
          </a-col>
          <a-col :span="10"
                 style="text-align: center; height: 380px; display: flex; align-items: center; justify-content: center;">
            <img alt="vs" src="/src/assets/pk/vs.png" style="width: 150px; height: 200px;"/>
          </a-col>
          <a-col :span="7">
            <UserBoard :user="opponent" :key="opponent"/>
          </a-col>
        </a-row>
      </a-layout-content>
      <a-layout-footer>
        <div class="start-match-btn" @click="startMatch">
          {{ startMatchText }}
        </div>
      </a-layout-footer>
    </a-layout>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import UserBoard from "../../components/pk/UserBoard.vue";
import {PkControllerService, UserScoreControllerService} from "../../apis/index.js";
import {Message} from "@arco-design/web-vue";
import {useRouter} from "vue-router";
import {useStore} from "vuex";

const router = useRouter();
const store = useStore();
const hour = ref(0);
const minute = ref(0);
const second = ref(0);
const startMatchFlag = ref(false);
const myself = ref({});
const opponent = ref(undefined);
const startMatchText = ref("开始匹配")
const timerInterval = ref();
let ws = null;

const startMatch = () => {
  startMatchFlag.value = !startMatchFlag.value;
  if (startMatchFlag.value) {
    timerInterval.value = setInterval(() => {
      second.value += 1;
      if (second.value === 60) {
        second.value = 0;
        minute.value += 1;
        if (minute.value === 60) {
          minute.value = 0;
          hour.value += 1;
        }
      }
    }, 1000)
    startMatchText.value = "取消"
    doStartMatch();
  } else {
    clearInterval(timerInterval.value);
    second.value = 0;
    hour.value = 0;
    minute.value = 0;
    startMatchText.value = "开始匹配";
    ws.close();
  }
}
const doStartMatch = async () => {
  const res = await PkControllerService.match();
  if (res.code === 200) {
    const token = res.data;
    connectWebSocket(token);
  } else {
    Message.error(res.msg);
  }
}

const connectWebSocket = (token) => {
  ws = new WebSocket("ws://localhost:8888/client/pk/" + token);
  ws.onopen = () => {
    console.log("前端建立连接");
    let msg = {
      event: "start",
    };
    ws.send(JSON.stringify(msg));
  }
  ws.onmessage = (e) => {
    console.log("前端收到消息：", e)
    const data = JSON.parse(e.data);
    if (data.status === "playing") {
      Message.success("匹配成功，即将进入对战页面")
      opponent.value = data.opponent;
      store.dispatch("pk/setMyself", myself.value);
      store.dispatch("pk/setOpponent", opponent.value);
      store.dispatch("pk/setProblemId", data.problemId);
      store.dispatch("pk/setWebsocket", ws);
      clearInterval(timerInterval.value);
      setTimeout(() => {
        router.replace({
          name: "PkQuestion",
        })
      }, 1000)
    } else if (data.status === "end") {
      Message.warning("对局已结束")
      setTimeout(() => {
        router.replace({
          name: "Pk",
        })
      }, 1000)
    }
  }
  ws.onerror = (e) => {
  }
  ws.onclose = (e) => {
    console.log("前端关闭连接");
  }

}

const getData = async () => {
  const res = await UserScoreControllerService.getUserScore();
  if (res.code === 200) {
    myself.value = res.data;
  } else {
    Message.error(res.msg);
  }
}

onMounted(() => {
  getData();
})
</script>

<style scoped>
.start-match-btn {
  width: 100%;
  height: 43px;
  text-align: center;
  background-image: url("src/assets/pk/bg-startmatch.png");
  background-repeat: no-repeat;
  background-position: center;
  line-height: 43px;
  font-size: 18px;
  color: white;
}

.start-match-btn:hover {
  cursor: pointer;
}

.timer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 0 auto;
  width: 186px;
  height: 92px;
  background-image: url("../../assets/pk/bg-timer.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  color: white;
}
</style>
